import Taro from "@tarojs/taro";

type FileUrl = string;

export const downloadFiles = (
  files: FileUrl[],
  callback?: (progress: number) => void
) => {
  let batches: FileUrl[][] = [];

  const fileCount = files.length;
  let downloadedCount = 0;
  let finishedBatchCount = 0;

  while (files.length) {
    batches.push(files.splice(0, 5));
  }

  const updateProgress = () => {
    downloadedCount++;
    if (callback) {
      callback(Math.round((downloadedCount / fileCount) * 100) / 100);
    }
  };

  const downloadBatch = (batchIndex: number) => {
    let downloadedBytes: number[] = [];
    const promises: Promise<any>[] = [];

    batches[batchIndex].forEach((url) => {
      downloadedBytes.push(0);

      const task = Taro.downloadFile({
        url,
        success: () => {
          updateProgress();
        },
        fail: (res) => {
          /**
           * NOTE:
           * When error occurs, assume file not found, and skip it.
           * So it won't block the UI
           */
          console.error(res.errMsg);
          updateProgress();
        },
      });
      promises.push(task);
    });

    Promise.all(promises).then(() => {
      finishedBatchCount++;
      if (finishedBatchCount < batches.length) {
        downloadBatch(finishedBatchCount);
      }
    });
  };

  downloadBatch(0);
};
